<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<%@ taglib prefix="his_fns" uri="/WEB-INF/tlds/his_fns.tld" %>

<div class="app">
    <section class="layout">
        <section class="main-content col-lg-12" id="expExportDiv">
            <div class="content-wrap">
                <div class="wrapper" style="bottom: 50px;">
                    <ul class="nav nav-tabs">
                        <li class="active">
                            <a href="#" onclick="loadDiv('mainCenterDiv','${ctx}/csm/expExport/index')">出库处理</a>
                        </li>
                    </ul>
                    <section class="panel panel-default">
                        <div class="panel-body">
                            <div class="table-responsive no-border">
                                <div class="datatable-top">
                                    <div class="pull-left">
                                        <form:form id="searchForm" modelAttribute="expExportDetail"
                                                   onsubmit="return loadDivForm('mainCenterDiv','searchFormDict','${ctx}/csm/expExport/index');"
                                                   method="post" class="form-inline">
                                            <div class="form-group">
                                                <label class=" control-label">出库类别：</label>
                                                <form:select path="expInoutClass.type" id="masterClass" htmlEscape="false" class="form-control" maxlength="1" data-parsley-required="true"
                                                        onchange="loadSupplier()">
                                                    <form:options items="${his_fns:getImpOrOutpList('0')}" itemLabel="inOutName" itemValue="type" htmlEscape="false" />
                                                </form:select>
                                            </div>

                                            <div class="form-group">
                                                <label class=" control-label">出库日期：</label>
                                                <input name="expExportMaster.exportDate" id="exportDate" htmlEscape="false" class="form-control Wdate" data-parsley-required="true" readonly/>
                                            </div>
                                            <div class="form-group">
                                                <label class=" control-label">收货单位：</label>
                                                <select class="form-control" id="supplier"></select>
                                            </div>
                                            <div class="form-group">
                                                <label class=" control-label">付款方式：</label>
                                                <form:select path="expExportMaster.accountType" id="accountType" class="form-control"  >
                                                    <form:option value="" label="" />
                                                    <form:options items="${fns:getDictList('ACCOUNT_TYPE')}" itemLabel="label" itemValue="value" htmlEscape="false" />
                                                </form:select>
                                            </div>
                                            <div class="form-group">
                                                <label class=" control-label">出库金额总计:</label>
                                                <input class="form-control" id="totalMoney" type="text" readonly>
                                            </div>
                                            <div class="form-group">
                                                    <input id="btnSubmit" class="btn btn-primary" type="button" onclick="saveExport()" value="保存"/>
                                                    <input id="addExp" class="btn btn-primary" type="button" value="添加" onclick="addExportItem()"/>
                                            </div>
                                        </form:form>
                                    </div>
                                </div>
                                <table id="contentTable" class="table table-bordered table-striped mg-t datatable">
                                    <thead>
                                    <tr>
                                        <th hidden>jsonText</th>
                                        <th hidden>编码</th>
                                        <th>品名</th>
                                        <th>型号</th>
                                        <th hidden>规格</th>
                                        <th hidden>单位代码</th>
                                        <th hidden>单位</th>
                                        <th hidden>包装数量</th>
                                        <th>规格</th>
                                        <th hidden>包装单位代码</th>
                                        <th>单位</th>
                                        <th hidden>厂家ID</th>
                                        <th>厂家</th>
                                        <th>入库价</th>
                                        <th>零售价</th>
                                        <th>批号</th>
                                        <th>有效期</th>
                                        <th>灭菌方式</th>
                                        <th>灭菌批号</th>
                                        <th>灭菌日期</th>
                                        <th>出库数量</th>
                                        <th hidden>当前库存</th>
                                        <th hidden>入库单号</th>
                                        <th hidden>入库主表ID</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                </table>
                            </div>
                        </div>
                    </section>
                </div>
            </div>
        </section>
        <%--右侧消耗品出库明细列表--%>
        <section class="main-content col-lg-4" style="display: none" id="expExportRightDiv">
            <div class="content-wrap" id="rigthCenterDiv">
            </div>
        </section>
    </section>
</div>
<script type="text/javascript">
    loadSupplier();
    function loadSupplier() {
        $("#supplier").html("");
        var exportClass = $('#masterClass').val();  //出库类别
        $.ajax({
            url: '${ctx}/csm/expSupplierCata/getSupplierOrStorageList?inoutType=' + '0' + '&type=' + exportClass,
            type: 'get',
            contentType: 'application/json',
            async: true,
            success: function (data, textStatus, jqXHR) {
                if (data.length > 0) {
                    if(typeof(data[0].supplierJc) == 'undefined'){
                        $.each(data, function (index, item) {
                            $("#supplier").append("<option value=''>" + '' + "</option>");
                            $("#supplier").append("<option value='" + item.storageCode + "'>" + item.storageName + "</option>");
                        });
                    }else{
                        $.each(data, function (index, item) {
                            $("#supplier").append("<option value=''>" + '' + "</option>");
                            $("#supplier").append("<option value='" + item.id + "'>" + item.supplierJc + "</option>");
                        });
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {

            }
        });
    }

    //设置出库日期为当前时间,不能编辑
    var date = new Date();
    var nowMonth = "";
    if(date.getMonth()+1 <= 9){
        nowMonth = "0" + (date.getMonth() + 1) + "";
    }else{
        nowMonth = (date.getMonth() + 1) + "";
    }
    var hours = "";
    if(date.getHours() < 10){
        hours = "0" + date.getHours();
    }else{
        hours = date.getHours();
    }
    var minutes = "";
    if(date.getMinutes() < 10){
        minutes = "0" + date.getMinutes();
    }else{
        minutes = date.getMinutes();
    }
    var seconds = "";
    if(date.getSeconds() < 10){
        seconds = "0" + date.getSeconds();
    }else{
        seconds = date.getSeconds();
    }
    var now = date.getFullYear() + "-" + nowMonth + "-" + date.getDate() + " " + hours + ":" + minutes + ":" + seconds;
    $('#exportDate').val(now);
    //出库金额总计
    $('#totalMoney').val(0.00);

    //弹出右边增加消耗品明细框
    function addExportItem(){
        $("#expExportDiv").attr("class","main-content col-lg-8");
        $("#expExportRightDiv").show('normal');
        return loadDiv('rigthCenterDiv','${ctx}/csm/expExport/form');
    }

    //删除一行消耗品
    function removeList(btn){
        $(btn).parent().parent().remove();
    }

    //修改消耗品
    function updateList(btn){
        var td = $(btn).parent().parent().children().eq(0).text();
        $("#expExportDiv").attr("class","main-content col-lg-8");
        $("#expExportRightDiv").show('normal');
        fillForm($("#inputForm"),td);
        $(btn).parent().parent().remove();
    }

    function saveExport(){
        var exportClass = $("#masterClass").val();  //出库类别
        var receiver = $('#supplier').val();     //收货单位
        var accountType = $('#accountType').val();  //付款方式
        if (exportClass.replace(/(^s*)|(s*$)/g, "").length == 0 || exportClass == null || typeof(exportClass) == 'undefined') {
            toastr.error("出库类别不能为空,请选择");
            return ;
        }
        if (receiver.replace(/(^s*)|(s*$)/g, "").length == 0 || receiver == null || typeof(receiver) == 'undefined') {
            toastr.error("收货方不能为空,请选择");
            return ;
        }
        if(exportClass == '3' && $.trim(accountType) == ''){
            toastr.error('退货出库,付款方式不能为空!');
            return ;
        }

        var list=$("table tr").find("td:eq(0)");
        if(list.length == 0){
            toastr.error('没有需要出库的数据!');
        }
        var dataList=[];
        var data={};
        for (var i=0;i<list.length;i++){
            data=jQuery.parseJSON(list[i].innerText);
            var expExportDetail = {};
            expExportDetail.infoId = data['expInfo.id'];
            expExportDetail.expCode = data['expCode'];
            expExportDetail.minSpec = data['minSpec'];
            expExportDetail.minUnits = data['minUnits'];
            expExportDetail.packageNum = data['packageNum'];
            expExportDetail.packageSpec = data['packageSpec'];
            expExportDetail.packageUnits = data['packageUnits'];
            expExportDetail.batchNo = data['batchNo'];
            expExportDetail.expireDate = data['expireDate'];
            expExportDetail.sterilizationMethod = data['sterilizationMethod'];
            expExportDetail.sterilizationBatchNo = data['expStock.sterilizationBatchNo'];
            expExportDetail.sterilizationDate = data['expStock.sterilizationDate'];
            if(exportClass == '3'){
                expExportDetail.purchasePrice = data['purchasePrice'];  //出库价
            }else{
                expExportDetail.purchasePrice = data['expPrice.retailPrice'];  //出库价
            }
            expExportDetail.quantity = Number(data['quantity']) * Number(data['packageNum']);
            var inventory = (Number(data['expStock.quantity']) - Number(data['quantity'])) * Number(data['packageNum']);   //计算出库后库存数
            expExportDetail.importMasterId = data['expStock.importMasterId'];
            expExportDetail.inventory = inventory;
            var expStock = {};
            expStock.id = data['expStock.id'];
            expStock.expName = data['expInfo.expDict.expName'];
//            expStock.discount = data.discount;
            expStock.infoId = data['expInfo.id'];
            expStock.documentNo = data['expStock.documentNo'];
            expStock.quantity = data['expStock.quantity'];
            data.expStock = expStock;
            var expPrice = {};
            expPrice.expInfo = data['expInfo.id'];
            expPrice.retailPrice = data['expPrice.retailPrice'];
            data.expPrice = expPrice;
            expExportDetail.expStock = expStock;
            var expExportMaster = {};
            expExportMaster.receiver = receiver;
            expExportMaster.exportClass = exportClass;
            expExportMaster.exportDate = $('#exportDate').val();
            expExportMaster.accountType = accountType;
            expExportDetail.expExportMaster = expExportMaster;
            dataList.push(expExportDetail);
        }

        var dataListJson = JSON.stringify(dataList);
        $.ajax({
            type: "POST",
            url: '${ctx}/csm/expExport/saveExport',
            data:dataListJson,
            'contentType': 'application/json',
            dataType: "json",
            success: function (data) {
                if (data.code == "success") {
                    toastr.success("消耗品出库成功");
                    layer.open({
                        title: "需要打印单据吗?",
                        type: 1,
                        area: ['300px', '150px'],
                        fixed: false, //不固定
                        skin: 'layui-layer-rim',
                        maxmin: true,
                        content:"",
                        btn: ['确定', '取消'],
                        yes: function (index, layero) {
                            printPdf('${ctx}/csm/expDetails/expExportDetailsPrint?masterId='+data.data);
                        }, no: function (index) {
                            layer.close(index);
                        }
                    });
                    return loadDiv('mainCenterDiv', '${ctx}/csm/expExport/index');
                } else {
                    toastr.error(data.data);
                }
            },
            error: function (data) {
                toastr.error('网络连接错误,请检查网络');
            }
        });
    }
</script>